<?php
namespace Api\Controller;
use Portal\Controller\CommonController;
use Library\Wx;

class ExternalController extends CommonController {

	function qrcodeurl(){
		$post = $this->objectToArray(json_decode(file_get_contents('php://input')));
		if(!$post['Id'] || !$post['Secret'] || !$post['terminalId']){
			$json['error'] = '请传入Id、Secrety、terminalId';
		}else{
			$qusers = D('QrcodeUsers')->where(array('name'=>$post['Id']))->find();
			if(!$qusers || $qusers['secret'] != $post['Secret']){
				$json['error'] = '请核对Id与Secrety';
			}else{
				if($qusers['status']==1){
					$scene = $post['terminalId'].'|=|'.$post['gameId'].'|=|'.$post['Id'];
					$url = Wx::getQRCode($scene,2);
					$json['url'] = $url['url'];
				}else{
					$json['error'] = '当前账号尚不可用';
				}
			}
		}
		echo json_encode($json);
	}
//	function test(){
////		$this->qrcodeusers = D("QrcodeUsers");
////		$this->qrcodeusers->where(array('name'=>'meiguan'))->save(array('request'=>array("exp","request+1")));
////		$Signature = str_replace('%','',urlencode(base64_encode(hash_hmac('sha1', 'bbt-9173',C('LOCAL_URL') ,true))));
////		echo $Signature;
//		$url = 'http://wxtest.baobaot.com/index.php?g=api&m=External&a=qrcodeurl';
//		$postjson = json_encode(array('Id'=>'9173','Secret'=>'XzL5BELbVidVCLFe2FwdHLxesgpA3D','terminalId'=>'wzx'));
//		$e = $this->http_post_json($url,$postjson);
//		dump($e);
//	}
	private function objectToArray($data) {
		if(is_object($data)){
			$data = get_object_vars($data);
		}
		if(is_array($data)){
			return array_map(null,$data);
		}
		else{
			return $data;
		}
	}
	function event($event){
		$this->qrcodeevent = D("QrcodeEvent");
		$tgid =explode("_", $event['EventKey']);
		if(count($tgid)==2){
			$eventkey =$tgid[1];
		}else{
			$eventkey =$tgid[0];
		}
		$eventkey = explode("|=|",$eventkey);
		$openid =$event["FromUserName"];
        $userinfo = Wx::getUserInfo($openid);
		if(count($eventkey)>2){
			$qusers = D('QrcodeUsers')->where(array('name'=>$eventkey[2]))->find();
			D('QrcodeUsers')->where(array('name'=>$eventkey[2]))->save(array('request'=>array("exp","request+1")));
			if($qusers['status']==1){
				$array = array(
					'terminalId'=>$eventkey[0],
					'gameId'=>$eventkey[1],
					'userInfo'=>array(
						'openid'=>$openid,
						'nickname'=>$userinfo['nickname'],
						'country'=>$userinfo['country'],
						'province'=>$userinfo['province'],
						'city'=>$userinfo['city'],
						'sex'=>$userinfo['sex'],
						'headimgurl'=>$userinfo['headimgurl'],
						)
					);
				$postjson = json_encode($array);
				$rjson = $this->http_post_json($qusers['callback'],$postjson);
				if($qusers['forwarding']){
					$rjson = $this->http_post_json($qusers['forwarding'],$postjson);
				}
			}
			if($qusers['status']==2 || !$qusers['status']){
				$array = array('Info'=>'管理员已关闭');
				$postjson = json_encode($array);
				$rjson = $this->http_post_json($qusers['callback'],$postjson);
				if($qusers['forwarding']){
					$rjson = $this->http_post_json($qusers['forwarding'],$postjson);
				}
			}
			$arr = array(
					'source'=>$eventkey[2],
					'terminalid'=>$eventkey[0],
					'gameid'=>$eventkey[1],
					'openid'=>$openid,
					'nickname'=>$userinfo['nickname'],
					'sex'=>$userinfo['sex'],
					'language'=>$userinfo['language'],
					'country'=>$userinfo['country'],
					'province'=>$userinfo['province'],
					'city'=>$userinfo['city'],
					'headimgurl'=>$userinfo['headimgurl'],
					'subscribe_time'=>$userinfo['subscribe_time'],
					'hits'=>array("exp","hits+1"),
					'postjson'=>$postjson,
					'status'=>$rjson[0],
					'receive'=>$rjson[1],
					);

			if($this->qrcodeevent->where(array('terminalid'=>$eventkey[0],'gameid'=>$eventkey[1],'openid'=>$openid))->find()){
				$this->qrcodeevent->where(array('terminalid'=>$eventkey[0],'gameid'=>$eventkey[1],'openid'=>$openid))->save($arr);
			}else{
				$this->qrcodeevent->add($arr);
			}
		}
	}
	function qrcode($event){
		$tgid =explode("_", $event['EventKey']);
		if(count($tgid)==2){
			$eventkey =$tgid[1];
		}else{
			$eventkey =$tgid[0];
		}
		$eventkey = explode("|=|",$eventkey);
		$openid =$event["FromUserName"];
        $userinfo = Wx::getUserInfo($openid);
		$this->qrcode_list_model = D("QrcodeList");
		$this->qrcode_list_user_model = D("QrcodeListUser");
		if(count($eventkey) < 2){
			$source = $eventkey[0];
			if($event['Event'] == 'unsubscribe'){
				$qlu = $this->qrcode_list_user_model->where(array('openid'=>$openid,'qtype' => 1))->order("id DESC")->find();
				$this->qrcode_list_model->where(array('id'=>$qlu['source']))->save(array('unsubscribe'=>array("exp","unsubscribe+1")));
			}
			if($event['Event'] == 'subscribe'){
				$this->qrcode_list_model->where(array('id'=>$source))->save(array('subscribe'=>array("exp","subscribe+1")));
			}
			if($event['Event'] == 'SCAN'){
				$this->qrcode_list_model->where(array('id'=>$source))->save(array('scanning'=>array("exp","scanning+1")));
			}
			if($this->qrcode_list_model->where(array('id'=>$source))->find()){
				$arr = array(
						'openid'=>$openid,
						'nickname'=>$userinfo['nickname'],
						'sex'=>$userinfo['sex'],
						'country'=>$userinfo['country'],
						'province'=>$userinfo['province'],
						'city'=>$userinfo['city'],
						'headimgurl'=>$userinfo['headimgurl'],
						'qtype' => 1,
						'source' => $source,
						'scanning'=>array("exp","scanning+1"),
				);
				if($this->qrcode_list_user_model->where(array('openid'=>$openid,'source'=>$source,'qtype' => 1))->find()){
					$this->qrcode_list_user_model->where(array('openid'=>$openid,'source'=>$source,'qtype' => 1))->save($arr);
				}else{
					$this->qrcode_list_user_model->add($arr);
				}
			}else{
				$arr = array(
						'openid'=>$openid,
						'nickname'=>$userinfo['nickname'],
						'sex'=>$userinfo['sex'],
						'country'=>$userinfo['country'],
						'province'=>$userinfo['province'],
						'city'=>$userinfo['city'],
						'headimgurl'=>$userinfo['headimgurl'],
						'source' => 0,
						'qtype' => 2,
						'scanning'=>array("exp","scanning+1"),
				);
				if($this->qrcode_list_user_model->where(array('openid'=>$openid,'qtype' => 2))->find()){
					$this->qrcode_list_user_model->where(array('openid'=>$openid,'qtype' => 2))->save($arr);
				}else{
					$this->qrcode_list_user_model->add($arr);
				}
			}
		}
	}


	private function http_post_json($url, $jsonStr){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json; charset=utf-8',
				'Content-Length: ' . strlen($jsonStr)
			)
		);
		$response = curl_exec($ch);
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
		curl_close($ch);
		$msg = $this->httpCode($httpCode);
		return array($msg, $response);
	}
	private function httpCode($hcode){
		$Code = array(
			array('id'=>100,'name'=>"Continue"),
			array('id'=>101,'name'=>"Switching Protocols"),

			array('id'=>200,'name'=>"OK"),
			array('id'=>201,'name'=>"Created"),
			array('id'=>202,'name'=>"Accepted"),
			array('id'=>203,'name'=>"Non-Authoritative Information"),
			array('id'=>204,'name'=>"No Content"),
			array('id'=>205,'name'=>"Reset Content"),
			array('id'=>206,'name'=>"Partial Content"),

			array('id'=>300,'name'=>"Multiple Choices"),
			array('id'=>301,'name'=>"Moved Permanently"),
			array('id'=>302,'name'=>"Found"),
			array('id'=>303,'name'=>"See Other"),
			array('id'=>304,'name'=>"Not Modified"),
			array('id'=>305,'name'=>"Use Proxy"),
			array('id'=>306,'name'=>"(Unused)"),
			array('id'=>307,'name'=>"Temporary Redirect"),

			array('id'=>400,'name'=>"Bad Request"),
			array('id'=>401,'name'=>"Unauthorized"),
			array('id'=>402,'name'=>"Payment Required"),
			array('id'=>403,'name'=>"Forbidden"),
			array('id'=>404,'name'=>"Not Found"),
			array('id'=>405,'name'=>"Method Not Allowed"),
			array('id'=>406,'name'=>"Not Acceptable"),
			array('id'=>407,'name'=>"Proxy Authentication Required"),
			array('id'=>408,'name'=>"Request Timeout"),
			array('id'=>409,'name'=>"Conflict"),
			array('id'=>410,'name'=>"Gone"),
			array('id'=>411,'name'=>"Length Required"),
			array('id'=>412,'name'=>"Precondition Failed"),
			array('id'=>413,'name'=>"Request Entity Too Large"),
			array('id'=>414,'name'=>"Request-URI Too Long"),
			array('id'=>415,'name'=>"Unsupported Media Type"),
			array('id'=>416,'name'=>"Requested Range Not Satisfiable"),
			array('id'=>417,'name'=>"Expectation Failed"),

			array('id'=>500,'name'=>"Internal Server Error"),
			array('id'=>501,'name'=>"Not Implemented"),
			array('id'=>502,'name'=>"Bad Gateway"),
			array('id'=>503,'name'=>"Service Unavailable"),
			array('id'=>504,'name'=>"Gateway Timeout"),
			array('id'=>505,'name'=>"HTTP Version Not Supported"),
		);
		foreach($Code as$c){
			if($c['id'] == $hcode){
				return $c['name'];
			}
		}
		return 'Unknown Code';
	}
}
